package org.csu.mypetstoreback.controller;

import org.csu.mypetstoreback.domain.Manager;
import org.csu.mypetstoreback.domain.SMSmap;
import org.csu.mypetstoreback.service.ManagerService;
import org.csu.mypetstoreback.service.zhenziSMS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
@SessionAttributes({"manager", "smsMap"})
public class ManagerController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private zhenziSMS sms;
    // 日志
    //private final Logger logger = LoggerFactory.getLogger(accountController.class);

    //跳转到登录界面
    @GetMapping("/manager/viewLoginForm")
    public String viewLoginForm(){
        return  "manager/login";
    }

    //管理员登录
    @PostMapping("/manager/login")
    public  String viewindex(String username, String password, Model model) {
        //logger.info("进入登录界面"); // 输出DEBUG级别的日志
        Manager manager = managerService.getManager(username, password);

//        System.out.println(manager.getUsername() + "&&&" + manager.getPassword());

        if (manager == null){
            model.addAttribute("msg", "用户名或密码错误");
            return  "manager/login";
        }else {
            model.addAttribute("manager", manager);
            return "catalog/main";
        }
    }

    //跳转到找回密码页面
    @GetMapping("/manager/viewFindPassWord")
    public String viewfindPassWord() {
        return "manager/findPassWord";
    }

    //提交自己的邮箱，找到属于这个邮箱的密码，发送邮件
    @PostMapping("/manager/findPassWord")
    public String findPassWord(String email) throws MessagingException{
        String oldPassword = managerService.findPassWord(email);
        System.out.println(oldPassword);

        return "manager/login";
    }

    @GetMapping("/manager/viewRegisterForm")
    public String viewRegisterForm(){
        return  "manager/register";
    }

    @PostMapping("/manager/register")
    public  String viewregister(Manager manager,Model model) {

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();//获取当前时间
        // Date转换成String类型储存
        manager.setEntryTime(ft.format(date));

        Manager exitManager = managerService.getManager(manager.getUsername());
        if (exitManager == null){
            managerService.insertManager(manager);
            return "manager/login";
        }else {
            model.addAttribute("error","Registeration failed,please change user name and enter information to register");
            return "manager/register";
        }

    }

    @GetMapping("/manager/profile")
    public  String viewprofile(){
        //logger.info("进入管理员界面"); // 输出DEBUG级别的日志
        return  "manager/profile";
    }

    @GetMapping("/manager/managerchange")
    public  String viewmanagerchange(){
        //logger.info("进入管理员修改信息界面"); // 输出DEBUG级别的日志
        return  "manager/managerchange";
    }

    //管理员提交修改好的个人信息
    @PostMapping("/manager/change")
    public  String managerchange(Manager manager, Model model) {

        String birthStr = manager.getBirthDay();//获取管理员填写的生日年月日字符串
        int birthYear = Integer.parseInt(birthStr.substring(0, 4));//截取前四位变成int生日年份

        SimpleDateFormat ft = new SimpleDateFormat("yyyy");
        Date date = new Date();//获取当前时间
        // Date转换成String类型储存
        String nowStr = ft.format(date);//获取当前年份字符串
        int nowYear = Integer.parseInt(nowStr);//变成int当前年份

        int ageStr = nowYear - birthYear;

        manager.setAge(ageStr);

        managerService.updateManager(manager);

        manager = managerService.getManager(manager.getUsername());
        model.addAttribute("manager", manager);

        return "manager/profile";
    }

    //跳转到找回密码页面
    @GetMapping("/manager/viewLoginBySMS")
    public String viewLoginBySMS() {
        return "manager/loginBySMS";
    }

    @GetMapping("/manager/GetCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception{

        HttpSession session = request.getSession();

        String phone = request.getParameter("phone");
        String tips;

        Manager manager = managerService.getManagerByPhone(phone);
        if (manager == null){
            tips = "no phone";
        }else {
            session.setAttribute("manager" , manager);

            Integer integer = sms.checkBalance();
            System.out.println(integer);

            Map<String, Object> smsMap = sms.sendMessage(phone,phone);
            String messageId = String.valueOf(smsMap.get("messageId"));

            System.out.println("GetCode messageId："+messageId);
            System.out.println(smsMap.get("messageId"));

            SMSmap mySMSmap = new SMSmap();
            mySMSmap.setMessageId(messageId);
            session.setAttribute("mySMSmap" , mySMSmap);

            tips = "Get Code Success";
        }

        System.out.println("手机号："+phone);
        PrintWriter out = response.getWriter();
        out.print(tips);
        out.flush();
        out.close();
    }

    //用手机号和验证码登录
    @GetMapping("/manager/loginBySMS")
    public void loginBySMS(HttpServletRequest request,HttpServletResponse response) throws Exception{
        HttpSession session = request.getSession();
        SMSmap smsMap = (SMSmap)session.getAttribute("mySMSmap");
        String cacheCode = request.getParameter("cacheCode");

        String messageId = smsMap.getMessageId();

        System.out.println("messageId：" + messageId + "&& cacheCode：" + cacheCode);

        Boolean bool = sms.checkMessage(messageId, cacheCode);
        System.out.println(bool);

        String tips;

        if (bool){
            tips = "Success";
        }else {
            tips = "Error";
        }

        PrintWriter out = response.getWriter();
        out.print(tips);
        out.flush();
        out.close();
    }

}
